package com.mk.shardingjdbcdemo.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 自定义分片规则
 */
public class MyCustomRule implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(Collection<java.lang.String> collection, PreciseShardingValue<String> preciseShardingValue) {
        /**
         * 1. 获取id值转换为哈希值取模 - id可能为负数所以要取绝对值
         * 2. collection为实际的分片表名称，通过取模计算出将数据具体放到哪一个分片表中保存
         */
        String id = preciseShardingValue.getValue();
        int i = Math.abs(id.hashCode()) % collection.size();
        String[] colls = collection.toArray(new String[0]);
        return colls[i];
    }
}
